package com.zhuzhe.mq.mqtype.rabbitmq.init;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;

/**
 * @author whh
 * @date 2020/08/24 20:31
 */
public class MQMessageHandleService implements ChannelAwareMessageListener {
    private static Logger log = LoggerFactory.getLogger("MQ");

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        byte[] body = message.getBody();
        String messageStr = new String(body);
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(messageStr);
            if (jsonObject == null) {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);// 消息丢弃
            }
            log.info("处理消息:" + jsonObject.toJSONString());
            // System.out.println("exchange:"+message.getMessageProperties().getReceivedExchange());
            String queue = message.getMessageProperties().getConsumerQueue();
            log.info("queue:" + queue);
            this.dealMessage(jsonObject.getString("dataType"), jsonObject.getString("data"));
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);// 确认消息消费成功
        } catch (JSONException e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);// 消息丢弃
            log.error("Message " + messageStr + ",处理失败");
        }
    }

    public void dealMessage(String dataType, String message) {}
}
